﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace DataAccessLayer.DAL
{
    public class ProductCategoryDAL
    {
        /// <summary>
        /// Get all children category of an parent category. Return root categories if parentID is NULL.
        /// </summary>
        /// <param name="parentID">ID of parent category, nullable.</param>
        /// <returns>List of all available childrent categories.</returns>
        public static List<ProductCategory> GetChildrenOfCategory(int? parentID)
        {
            using (var context = new ReverseAuctionEntities())
            {
                if (parentID.HasValue)
                {
                    return context.ProductCategories.Where(p => p.ParentID == parentID && p.Active == (int)ProductCategoryStatus.Active).ToList();
                }
                else
                {
                    return context.ProductCategories.Where(p => !p.ParentID.HasValue && p.Active == (int)ProductCategoryStatus.Active).ToList();
                }
            }
        }

        public static ProductCategory GetAllSeller(int productID)
        {
            using (var context = new ReverseAuctionEntities())
            {
                return context.ProductCategories.Include("Users").SingleOrDefault(u => u.ID == productID);
            }
        }

        public static ProductCategory GetByID(int productID)
        {
            using (var context = new ReverseAuctionEntities())
            {
                return context.ProductCategories.SingleOrDefault(u => u.ID == productID);
            }
        }

        public static List<ProductCategory> GetCategories()
        {
            List<ProductCategory> list = new List<ProductCategory>();
            using (var context = new ReverseAuctionEntities())
            {
                //String sql = "it.Active==" + (int)ProductCategoryStatus.Active;
                string sql = string.Format("it.Active=={0}", (int)ProductCategoryStatus.Active);
                var result = context.ProductCategories.Where(sql).OrderBy("it.Depth");
                foreach(var item in result)
                {
                    if (item.ParentID == null)
                    {
                        list.Add(item);
                    }
                }
            }
            return list;
        }
    }
}
